package org.wakeful.cfg;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author atila
 */
public final class Wed {

   private static KeyGenerator kGenerator;
   private static SecretKey secretKey;
   private static SecretKeySpec specKey;
   private static Cipher cipher;
   
   private Wed() {
   }

   static {
      try {
         kGenerator = KeyGenerator.getInstance("Blowfish");
         secretKey = kGenerator.generateKey();
         byte[] bytes = secretKey.getEncoded();
         specKey = new SecretKeySpec(bytes, "Blowfish");
         cipher = Cipher.getInstance("Blowfish");
      } catch (Throwable ex) {
         throw new ExceptionInInitializerError(ex);
      }
   }

   public static String encrypt(String phrase) throws Exception {
      byte[] encrypted = null;
      try {
         cipher.init(Cipher.ENCRYPT_MODE, specKey);
         encrypted = cipher.doFinal(phrase.getBytes());
      } catch (Exception ex) {
         throw new Exception(ex);
      }
      return new String(encrypted);
   }

   public static String decrypt(String phrase) throws Exception {
      byte[] decrypted = null;
      try {
         decrypted = cipher.doFinal(phrase.getBytes());
      } catch (Exception ex) {
         throw new Exception(ex);
      }
      return new String(decrypted);
   }
}
